package com.kk.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.kk.Entry.R;
import com.kk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        if (url.contains("login")) {
            return true;
        }
        String token = request.getHeader("token");
        if (token == null) {
            R<Object> notLogin = R.fail("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(notLogin);
            response.getWriter().write(jsonString);
            return false;
        }
        try {
            Claims parsedJwt = JwtUtils.parseJwt(token);

        } catch (Exception e) {
            R<Object> notLogin = R.fail("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(notLogin);
            response.getWriter().write(jsonString);
            return false;
        }
        return true;

    }
}
